<template>
  <view class="flex flex-col w-[750rpx] min-h-screen bg-gray-100">
    <!-- 登录状态检查组件 -->
    <LoginStatusCheck ref="loginStatusRef" />

    <view class="bg-white rounded-[20rpx] mb-[24rpx] overflow-hidden">
      <nut-swiper :auto-play="3000" :loop="true" class="rounded-t-[20rpx]" :init-page="currentImageIndex"
        @change="onSwiperChange">
        <nut-swiper-item v-for="(image, index) in productImages" :key="index" class="swiper-item">
          <image :src="useImage(image)" class="w-full h-[400rpx] object-cover" mode="aspectFill" />
        </nut-swiper-item>
        <template #page>
          <view class="swiper-pagination">{{ currentImageIndex + 1 }}/{{ productImages.length }}</view>
        </template>
      </nut-swiper>
    </view>
    <part1 :info="productInfo" :imgs="productImages" />
    <info :info="productInfo" />
    <part2 :info="productInfo" v-model:quantity="quantity" :edit-mode="!tempShopStore.showAdd" />
    <care />

    <view class="bg-white p-[32rpx] flex border-t border-gray-200 gap-[30rpx]">
      <view class="flex-1 w-full h-[96rpx] bg-orange-500 rounded-[48rpx] flex items-center justify-center"
        @tap="addToCart">
        <text class="text-white text-[36rpx] font-bold">加入购物车</text>
      </view>

      <view v-if="!tempShopStore.showAdd"
        class="flex-1 w-full h-[96rpx] bg-green-500 rounded-[48rpx] flex items-center justify-center" @tap="handlePay">
        <text class="text-white text-[36rpx] font-bold">去支付</text>
      </view>
    </view>


  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { useImage } from '@/hooks'
import { useAuthStore, useCartStore } from '@/store';
import { storeToRefs } from 'pinia';
import type { CartItem } from '@/store/modules/cart';
import part1 from './components/part1.vue'
import part2 from './components/part2.vue'
import care from '@/components/basic-comm/care.vue';
import info from './components/info.vue';
import LoginStatusCheck from '@/components/login-status-check/index.vue';

import { useTempShopStore } from '@/store/modules/shop/temp';
import { request } from '@/service/request';
import { useMedicationStore } from '@/store/modules/medication';
const tempShopStore = useTempShopStore();
const cartStore = useCartStore();
const { nurseUser } = storeToRefs(useAuthStore());
const medicationStore = useMedicationStore();
console.log('nurseUser', nurseUser.value)

definePageConfig({
  //   navigationStyle: 'custom',
  navigationBarTitleText: '商品详情'
})

// 注册组件
const components = {
  LoginStatusCheck
}

// 商品信息
const productInfo = ref<any>({})

// 购买数量
const quantity = ref(1)

// 登录状态检查组件引用
const loginStatusRef = ref()

// 轮播图相关
const currentImageIndex = ref(0)
const productImages = computed(() => {
  if (productInfo.value.pic) {
    // 如果有多张图片，用逗号分隔
    const pics = productInfo.value.pic.split(',').filter((pic: string) => pic.trim())
    return pics.length > 0 ? pics : [productInfo.value.pic]
  }
  return []
})

// 计算总价
const totalPrice = computed(() => {
  const price = parseFloat(productInfo.value.price || 0)
  return price * quantity.value
})

// 页面加载时从缓存读取商品信息
onMounted(() => {
  console.log("tempShopStore.showAdd", tempShopStore.showAdd)
  loadProductInfo()
})

// 从本地缓存读取商品信息
const loadProductInfo = () => {
  try {
    const cachedProduct = Taro.getStorageSync('selectedProduct')
    if (cachedProduct) {
      productInfo.value = cachedProduct
      console.log('从缓存读取商品信息:', cachedProduct)
      getStandardPrice()
    } else {
      console.log('缓存中没有商品信息')
      Taro.showToast({
        title: '商品信息不存在',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('读取商品缓存失败:', error)
    Taro.showToast({
      title: '读取商品信息失败',
      icon: 'none'
    })
  }
}

const getStandardPrice = () => {
  if (productInfo.value.standardCode) {
    medicationStore.loadSku(productInfo.value.standardCode || 1);
    // request.get('/standard_price/standardPrice/list', {
    //   code: productInfo.value.standardCode,
    // }, {
    //   useErrMsg: true
    // }).then((res:any) => {
    //   console.warn("res==== info price", res)
    //   if(res.success.records.length > 0) {
    //     // productInfo.value.price = res.success.records;
    //   }
    //     else{
    //       Taro.showToast({
    //         title: '商品规格不存在',
    //         icon: 'none'
    //       })
    //   }
    // })
  }
  else{
    Taro.showToast({
      title: '商品规格不存在',
      icon: 'none'
    })
  }
}

// 从组件获取登录状态
const getLoginStatus = () => {
  return loginStatusRef.value?.isLoggedIn || false
}

// 检查登录并显示提示
const requireLogin = (options?: { title?: string, content?: string }) => {
  return loginStatusRef.value?.requireLogin(options) || false
}

// 返回上一页
const goBack = () => {
  Taro.navigateBack()
}

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 增加数量
const increaseQuantity = () => {
  quantity.value++
}

// 数量输入改变
const onQuantityChange = (e: any) => {
  const value = parseInt(e.detail.value)
  if (value >= 1) {
    quantity.value = value
  } else {
    quantity.value = 1
  }
}

// 轮播图切换事件
const onSwiperChange = (index: number) => {
  currentImageIndex.value = index
}

// 添加到购物车
const addToCart = () => {
  // 检查登录状态
  if (!requireLogin({
    title: '提示',
    content: '请先登录才能添加商品到购物车'
  })) {
    return
  }

  if (productInfo.value && typeof productInfo.value.price === 'number') {
    if (tempShopStore.showAdd) {
      tempShopStore.addGoods(productInfo.value, quantity.value)
      Taro.showToast({
        title: '添加成功',
        icon: 'none'
      });
      tempShopStore.closeAddDialog();
      Taro.navigateBack();
    } else {
      cartStore.addToCart(productInfo.value as Omit<CartItem, 'quantity'>);
    }
  } else {
    Taro.showToast({
      title: '该商品无法添加',
      icon: 'none'
    });
  }
};

// 支付处理 - 跳转到订单确认页面
const handlePay = () => {
  // 检查登录状态
  if (!requireLogin({
    title: '提示',
    content: '请先登录才能购买商品'
  })) {
    return
  }

  // 打印商品信息和数量
  console.log('=== 立即支付信息 ===')
  console.log('商品信息:', productInfo.value)
  console.log('购买数量:', quantity.value)
  console.log('单价:', productInfo.value.price)
  console.log('总价:', totalPrice.value.toFixed(2))
  console.log('===============')

  // 准备单个商品的订单数据
  const singleProductData = {
    items: [{
      id: productInfo.value.id,
      typeName: productInfo.value.typeName,
      // price: productInfo.value.price,
      price: medicationStore.sku.cur?.price || 0,
      quantity: quantity.value,
      pic: productInfo.value.pic,
      goodsType_dictText: productInfo.value.goodsType_dictText,
      selected: true
    }],
    totalPrice: totalPrice.value.toFixed(2),
    totalItems: quantity.value
  }

  // 将单个商品数据存储到本地存储中，模拟购物车数据格式
  Taro.setStorageSync('cart_checkout_data', singleProductData)

  console.log('已准备单个商品数据:', singleProductData)

  // 跳转到订单确认页面
  Taro.navigateTo({
    url: `/package/goodspay/index?fromCart=true&fromSingle=true`
  })
}


</script>

<style lang="scss">
/* 页面样式 */
page {
  background-color: #f5f5f5;
}

/* 输入框样式 */
input {
  outline: none;
}

/* 轮播图样式 */
.swiper-item {
  height: 400rpx;
}

.swiper-pagination {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}
</style>